<template>
<div>
    <el-tag
  :key="tag.id"
  v-for="tag in dynamicTags"
  closable
  @close="handleClose(tag)"
  :disable-transitions="false">
  {{tag}}
</el-tag>
<el-button v-if="isDialog" class="button-new-tag"  @click="showFileTree">+ 培训教材</el-button>
<el-dialog title="培训教材" :visible.sync="dialogVisible" :modal="false" :modal-append-to-body="false">
    <el-input 
  placeholder="输入关键字进行过滤"
  v-model="filterText">
</el-input>
  <el-tree class="filter-tree" ref="file_Tree" :filter-node-method="filterNode" lazy :load="loadNode1" :show-checkbox="showCheckbox" node-key="id" 
  :check-strictly="dataCheckStrictly"
  :default-expand-all="dea"
  :props="defaultProps"
  :isDialog="isDialog"
  @node-expand="handleNodeExpand"
  @check-change="handleCheckChange" 
  :highlight-current="true" >
  </el-tree>
</el-dialog>
  <el-input v-if="!isDialog"
  placeholder="输入关键字进行过滤"
  v-model="filterText">
</el-input>
 <el-tree v-if="!isDialog" ref="file_Tree" :filter-node-method="filterNode" lazy :load="loadNode1" :show-checkbox="showCheckbox" node-key="id" 
  @node-expand="handleNodeExpand"
  :check-strictly="checkStrictly"
  :default-expand-all="dea"
  :props="defaultProps"
  :isDialog="isDialog"
  @check-change="handleCheckChange"
  :highlight-current="true" >
  </el-tree>
  </div>
</template>

<script>
import { orgTree, fileTree } from "@/api/org";
import vue from "vue";
export default {
  props: {
    dcksValue: [Array], //生成教材培训树时默认勾选的节点的值，传入类型为数组
    dcksLabel: [Array], //生成教材培训树时默认勾选的节点的描述，传入类型为数组
    dcksQNKey: [Array], //生成教材培训树时默认勾选的节点的七牛key，传入类型为数组
    checkStrictly: {
      type: Boolean,
      default: true
    }, //在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false;如果关联则组织树默认为全展开，不关联则不展开
    isDialog: {
      type: Boolean,
      default: true
    }, //是否作为弹出框显示
    name, //弹出按钮名称
    isMultiple: {
      type: Boolean,
      default: true
    }, //是否可以多选 默认为多选
    showCheckbox: {
      type: Boolean,
      default: true
    } //是否显示勾选框 默认为显示
  },
  data() {
    return {
      filterText: "",
      i: 0,
      orgData: [], //初始化树的数据
      filesData: [], //初始化树的数据
      tagLabel: [],
      cksValue: [],
      cksLabel: [],
      cksQNKey: [],
      defaultProps: {
        label: "label",
        children: "children",
        isLeaf: "leaf"
      },
      dynamicTags: {
        type: Array,
        default: []
      },
      dataCheckStrictly: this.checkStrictly,
      dialogVisible: false,
      dea: false //是否展开组织树
    };
  },
  async created() {
    console.log("fileTree.created");
    if (!this.isMultiple) {
      this.dataCheckStrictly = true;
    }
    if (!this.dataCheckStrictly) {
      this.dea = true;
    }
    if (!this.isDialog) {
      // console.log("fileTree.isNotDialog",this.dcksValue,this.dcksQNKey,this.dcksLabel);
      // console.log("fileTree.isNotDialog_cks",this.cksValue,this.cksQNKey,this.cksLabel,this.tagLabel);
      this.cksValue = this.dcksValue;
      this.cksQNKey = this.dcksQNKey;
      this.cksLabel = this.dcksLabel;
      this.tagLabel = [...this.cksLabel];
      this.tagLabel.forEach((item, index) => {
        const a = index + 1;
        const c = a + "." + item;
        this.tagLabel[index] = c;
      });
    }
    this.dynamicTags = this.tagLabel;
  },
  methods: {
    filterNode(value, data) {
      console.log("value", value);
      console.log("data", data);
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
      console.log("data", data);
      console.log("value", value);
    },
    loadNode1(node, resolve) {
      console.log("loadNode1", node);
      if (node.level === 0) {
        return resolve([{ label: "培训教材", id: "1568", disabled: true }]);
      } else {
        fileTree(node.data.id)
          .then(response => {
            this.filesData = response.data;
            console.log(this.filesData);
            const nodes = response.data["nodes"];
            console.log("nodes", nodes);
            const files = response.data["files"];
            console.log("files", files);
            const data = [...nodes, ...files];
            console.log("data", data);
            resolve(data);
            //   console.log("this.cksValue",this.cksValue)
            //  this.$refs.file_Tree.setCheckedKeys(this.cksValue);
          })
          .catch(err => {
            this.fetchSuccess = false;
            console.log(err);
          });
      }
    },
    handleNodeExpand(data) {
      console.log("this.nodeExpand.data", data);
      this.$refs.file_Tree.setCheckedKeys(this.cksValue);
    },
    showFileTree() {
      this.dialogVisible = true;
      // this.orgTreeInit();
    },
    handleClose(tag) {
      console.log("this.handleClose.tag", tag);
      this.cksValue = this.dcksValue;
      this.cksLabel = this.dcksLabel;
      this.cksQNKey = this.dcksQNKey;
      this.tagLabel = this.dynamicTags;
      const tagIndex = this.tagLabel.indexOf(tag);
      // if()
      this.cksValue.splice(tagIndex, 1);
      this.cksLabel.splice(tagIndex, 1);
      this.tagLabel.splice(tagIndex, 1);
      this.cksQNKey.splice(tagIndex, 1);
      // for (const node of this.$refs.file_Tree.getCheckedNodes()) {
      //   if (tag == node.label) {
      //     const idIndex = this.cksValue.indexOf(node.id);
      //     this.cksValue.splice(idIndex, 1);
      //     this.cksLabel.splice(idIndex, 1);
      //     this.cksQNKey.splice(idIndex, 1);
      //   }
      // }
      // this.cksLabel.forEach((item,index) => {const a=index+1; const c=a+'.'+item;alert(c);this.cksLabel[index]=c;});
      this.dynamicTags = this.tagLabel;
      this.$emit("update:dcksLabel", this.cksLabel);
      this.$emit("update:dcksValue", this.cksValue);
      this.$emit("update:dcksQNKey", this.cksQNKey);
      this.$refs.file_Tree.setCheckedKeys(this.cksValue);
    },

    /**
     * 获取树的data值
     */
    async getOrgData() {
      this.$store.dispatch("openLoading");
      orgTree().then(response => {
        this.orgData = response.data.items;
      });
      this.$store.dispatch("closeLoading");
    },

    /**
     * 重新获取树的data值，并根据父页面传过来的值初始化勾选状态
     */
    async fileTreeInit() {
      console.log("orgTreeInit");
      // await this.getOrgData();
      // vue.nextTick(_ => {
      //   this.$refs.file_Tree.setCheckedKeys(this.dcksValue);
      // });
      this.$refs.file_Tree.setCheckedKeys(this.dcksValue);
      this.cksLabel = this.dcksLabel;
      this.tagLabel = [];
      this.tagLabel = [...this.dcksLabel];
      this.tagLabel.forEach((item, index) => {
        const a = index + 1;
        const c = a + "." + item;
        this.tagLabel[index] = c;
      });
      this.dynamicTags = this.tagLabel;
    },
    /**
     * 树节点勾选状态变更时，更改tag内容
     */
    handleCheckChange(node, isChecked, isClildChecked) {
      this.i++;
      console.log("handleCheckChange.i", this.i);
      console.log("handleCheckChange.node", node);
      console.log("handleCheckChange.isChecked", isChecked);
      console.log("handleCheckChange.dynamicTags1", this.dynamicTags);
      console.log("handleCheckChange.dcksLabel", this.dcksLabel);
      if (this.isMultiple) {
        this.cksValue = this.dcksValue;
        this.cksLabel = this.dcksLabel;
        this.cksQNKey = this.dcksQNKey;
        if (!this.cksValue.includes(node.id) && isChecked) {
          this.$refs.file_Tree.setCurrentNode(node);
          this.cksValue.push(node.id);
          this.cksLabel.push(node.label);
          this.cksQNKey.push(node.QNKey);
        } else if (this.cksValue.includes(node.id) && !isChecked) {
          const idIndex = this.cksValue.indexOf(node.id);
          this.cksValue.splice(idIndex, 1);
          this.cksLabel.splice(idIndex, 1);
          this.cksQNKey.splice(idIndex, 1);
        }
        this.tagLabel = [...this.cksLabel];
        this.tagLabel.forEach((item, index) => {
          const a = index + 1;
          const c = a + "." + item;
          this.tagLabel[index] = c;
        });
        this.dynamicTags = this.tagLabel;
        this.$emit("update:dcksLabel", this.cksLabel);
        this.$emit("update:dcksValue", this.cksValue);
        this.$emit("update:dcksQNKey", this.cksQNKey);
      } else {
        if (this.i % 2 == 0) {
          if (isChecked) {
            this.cksValue = [];
            this.cksLabel = [];
            this.cksQNKey = [];
            this.$refs.file_Tree.setCheckedNodes([]);
            this.$refs.file_Tree.setCheckedNodes([node]);
            this.cksValue.push(node.id);
            this.cksLabel.push(node.label);
            this.cksQNKey.push(node.QNKey);
          } else if (!isChecked) {
            this.$refs.file_Tree.setCheckedNodes([]);
            this.cksValue = [];
            this.cksLabel = [];
            this.cksQNKey = [];
          }
        } else if (isChecked) {
          this.cksValue = [];
          this.cksLabel = [];
          this.$refs.file_Tree.setCheckedNodes([node]);
          this.cksValue.push(node.id);
          this.cksLabel.push(node.label);
          this.cksQNKey.push(node.QNKey);
        }
        console.log("handleCheckChange.this.cksLabel", this.cksLabel);
        console.log("handleCheckChange. this.cksValue", this.cksValue);

        this.$emit("update:dcksLabel", this.cksLabel);
        this.$emit("update:dcksValue", this.cksValue);
        this.$emit("update:dcksQNKey", this.cksQNKey);
      }
      this.tagLabel = [...this.cksLabel];
      this.tagLabel.forEach((item, index) => {
        const a = index + 1;
        const c = a + "." + item;
        this.tagLabel[index] = c;
      });
      this.dynamicTags = this.tagLabel;
      console.log("handleCheckChange.dynamicTags2", this.dynamicTags);
    }
  },
  watch: {
    dcksValue(curVal, oldVal) {
      console.log("watch.dcks", curVal, oldVal);
      if (curVal != oldVal) {
        this.fileTreeInit();
      }
    },
    filterText(val) {
        console.log("filterText",val);
      this.$refs.file_Tree.filter(val);
    }
  }
};
</script>
